using B.S.XZYData.Api.Read.Application.Command.Team;
using B.S.XZYData.Domain.RBAC;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;

namespace B.S.XZYData.Api.Read.Application.Handler.Team
{
    public class GetTeamMemberPageHandler : IRequestHandler<GetTeamMemberPageCommand, ApiPageing<TeamMemberDTO>>
    {
        private readonly IBaseRepository<TeamMember> teamMemberRepo;
        private readonly IBaseRepository<AccountModel> accountRepo;

        public GetTeamMemberPageHandler(IBaseRepository<TeamMember> teamMemberRepo, IBaseRepository<AccountModel> accountRepo)
        {
            this.teamMemberRepo = teamMemberRepo;
            this.accountRepo = accountRepo;
        }

        public async Task<ApiPageing<TeamMemberDTO>> Handle(GetTeamMemberPageCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPageing<TeamMemberDTO>();
            try
            {
                // 获取所有班组成员
                var teamMembers = teamMemberRepo.GetAll().Where(x => !x.IsDeleted).ToList();
                
                // 获取所有用户信息用于显示创建人和修改人
                var accounts = accountRepo.GetAll().Where(x => !x.IsDeleted).ToList();
                
                // 应用过滤条件
                if (request.TeamId.HasValue)
                {
                    teamMembers = teamMembers.Where(x => x.TeamId == request.TeamId.Value).ToList();
                }
                
                if (!string.IsNullOrEmpty(request.MemberName))
                {
                    teamMembers = teamMembers.Where(x => x.MemberName.Contains(request.MemberName)).ToList();
                }
                
                if (!string.IsNullOrEmpty(request.MemberRealName))
                {
                    teamMembers = teamMembers.Where(x => x.MemberRealName.Contains(request.MemberRealName)).ToList();
                }

                // 构建结果
                var result = new List<TeamMemberDTO>();
                foreach (var member in teamMembers)
                {
                    var creator = accounts.FirstOrDefault(a => a.Id == member.CreatorId);
                    var modifier = member.ModifierId.HasValue ? accounts.FirstOrDefault(a => a.Id == member.ModifierId.Value) : null;
                    
                    result.Add(new TeamMemberDTO
                    {
                        Id = member.Id,
                        TeamId = member.TeamId,
                        MemberName = member.MemberName,
                        MemberRealName = member.MemberRealName,
                        Phone = member.Phone,
                        CreateTime = member.CreateTime,
                        Creator = creator?.RealName ?? "未知",
                        ModifyTime = member.ModifyTime,
                        Modifier = modifier?.RealName ?? string.Empty
                    });
                }

                // 排序和分页
                var orderedResult = result.OrderByDescending(x => x.CreateTime).ToList();
                var totalCount = orderedResult.Count;
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.Size);
                var pageData = orderedResult.Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();

                res.TotaCount = totalCount;
                res.TotaPage = totalPage;
                res.PageData = pageData;
                res.Msg = "查询班组成员列表成功!";
                res.Code = ApiEnum.Success;
                return await Task.FromResult(res);
            }
            catch (Exception ex)
            {
                res.Msg = "查询班组成员列表异常!" + ex.Message;
                res.Code = ApiEnum.Error;
                return await Task.FromResult(res);
            }
        }
    }
}
